<?php
// To delete user from the database
if(isset($_POST['action']))
{
    $db = new Database();
    $auth = Auth::getAuth('current_user');
    $userID = $auth['id'];
    $timezone = "Asia/Manila";
    if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
    if($_POST['action']=="deleteUser"){
        $ID = $_POST['ID'];
        $is_active = "0";
        //$fields = array('is_active'=>$is_active);
        $conditions = array('id'=>$ID);
        //$update = $db->update('tbuser',$fields,$conditions);
        $update = $db->delete('tbuser',$conditions);
        echo "User was successfully deleted.";
	$audit = array(
			"user_id"=>$userID,
			"action_id"=>6,
			"affected_table"=>"tbuser",
			"affected_record"=>$ID,
			"datetime"=>date("Y-m-d  H:i:s"),
			"is_active"=>1
			);
	$db->insert("tbaudit_trail",$audit);
    }elseif($_POST['action']=="editUser"){
        $id = $_POST['ID'];
        $username = $_POST['username'];
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $loa = $_POST['loa'];
        $password = $_POST['password'];
        if(empty($username) or empty($firstname) or empty($lastname)){
            echo "There's an Empty Field.";
        }else{
            //checking for validation for sting name
            if(checkstrname($firstname)==0 or checkstrname($lastname)==0){
                echo "Please Input Correct Format of your firstname and lastname.";
            }else{
                //checking for username
                $query = $db->query("SELECT * FROM tbuser WHERE username='$username' and id !='$id'","numrows");
                if($query>0){
                    echo "Username is already Taken.";
                }else{
		    if(empty($password)){
		    $set = array('username'=>$username,
                     'userlevel_id'=>$loa,
                     'firstname'=>$firstname,
                     'lastname'=>$lastname);
		    }else{
                    $set = array('username'=>$username,
                     'userlevel_id'=>$loa,
                     'firstname'=>$firstname,
                     'lastname'=>$lastname,
                     'password'=>md5($password));
		    }
                    $conditions = array("id"=>$id);
                    $db->update("tbuser",$set,$conditions);
                    echo 1;
		    $db->insert('tbuser',$insert);
		    $audit = array(
				    "user_id"=>$userID,
				    "action_id"=>5,
				    "affected_table"=>"tbuser",
				    "affected_record"=>$id,
				    "datetime"=>date("Y-m-d  H:i:s"),
				    "is_active"=>1
				    );
		    $db->insert("tbaudit_trail",$audit);
                }
            }
        }
    }elseif($_POST['action']=="addUser"){
        $username = $_POST['username'];
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $loa = $_POST['loa'];
        $password = $_POST['password'];
        //checking for empty
        if(empty($username) or empty($firstname) or empty($lastname) or empty($password)){
            echo "Please fill those required fields.";
        }else{
            //checking for validation for sting name
            if(checkstrname($firstname)==0 or checkstrname($lastname)==0){
                echo "Please input the correct format for your name.";
            }else{
                //checking for username
                $query = $db->query("SELECT * FROM tbuser WHERE username='$username'","numrows");
                if($query!=0){
                    echo "Username is already taken.";
                }else{
                    $insert = array('username'=>$username,
                     'userlevel_id'=>$loa,
                     'firstname'=>$firstname,
                     'lastname'=>$lastname,
                     'password'=>md5($password),
                     'is_active'=>1);
                    $affected_record_id = $db->insert('tbuser',$insert);
		    $audit = array(
				    "user_id"=>$userID,
				    "action_id"=>4,
				    "affected_table"=>"tbuser",
				    "affected_record"=>$affected_record_id,
				    "datetime"=>date("Y-m-d  H:i:s"),
				    "is_active"=>1
				    );
		    $db->insert("tbaudit_trail",$audit);
		    echo "New user was successfully saved.";
                }
            }
        }
        /**/
    }elseif($_POST['action']=="userSearch")
    {
        $value = $_POST['value'];
        $textfield = "edi_textfield display"; // for textfield of edit.
        $selection = "editselection display"; // for selection of edit.
        $page = $_POST['page'];
        $cur_page = $page;
        $page -= 1;
        $per_page = 10; // Per page
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;
        $start = $page * $per_page;
	$action = $_POST['action'];
	//sort
	$markSortUser = @$_POST['markSortUser'];//for toggle of desc and asc 
	$fieldToSort = @$_POST['sortUserRel']; //field to sort
	$sortfield = " ORDER BY u.id "; // default field to sort
	if(!empty($fieldToSort)){
	    $sortfield = " ORDER BY $fieldToSort ";
	}
	$sortType = " ASC ";
	//condition for sorting if desc or asc
	if($markSortUser%2==0){
	    $sortType = " ASC ";
	}else{
	    $sortType = "DESC";
	}
	$sort =  $sortfield.$sortType; // concatinate sort
	//echo $sort;
        $finaldata.= "
        <table border='0' id='table_accomodation' class='table_accomodation'>
			    <thead>
				<tr>
				    <th class='sortuser' rel='username'>Username</th>
				    <th class='sortuser' rel='firstname'>Firstname</th>
				    <th class='sortuser' rel='lastname'>Lastname</th>
				    <th class='sortuser' rel='userlevel' width='100'>Level of Access</th>
                                    <th class='sortuser' rel='u.id' >Password</th>
				    <th class='sortuser' rel='u.id' colspan='2'>Actions</th>
				</tr>
			    </thead>
			    <tbody id='searchUserTable'>";
        if(!empty($value))
        {
	    $queryString = "SELECT u.id as id, firstname,lastname,username,password,userlevel as loa FROM tbuser u
				left join tbuserlevel ul on u.userlevel_id = ul.id WHERE
                                (username LIKE '%$value%'
                                OR firstname LIKE '%$value%'
                                OR lastname LIKE '%$value%'
                                )
                                AND u.is_active=1";
				
            $users = $db->query($queryString." $sort LIMIT $start, $per_page", "array");
            $count = $db->query($queryString, "numrows");
            $no_of_paginations = ceil($count / $per_page);
        }
        else{
	    $queryString = "SELECT u.id as id, firstname,lastname,username,password,userlevel as loa FROM tbuser u
				left join tbuserlevel ul on u.userlevel_id = ul.id
				WHERE u.is_active= 1";
				
            $users = $db->query($queryString." $sort LIMIT $start, $per_page", "array");
            $count = $db->query($queryString, "numrows");
            $no_of_paginations = ceil($count / $per_page);
        }
        if($count>0){
        foreach($users as $data)
        {
        $finaldata.=
        '<tr id="deleteRow_'.$data['id'].'">
            <td>
                <span id="username_'.$data['id'].'">
                    '.$data['username'].'
                </span>
                <input type="text" name="" id="editUsername_'.$data['id'].'" class="'.$textfield.'" value="'.$data['username'].'"/>
            </td>
            <td>
                <span id="firstname_'.$data['id'].'">
                    '.$data['firstname'].'
                </span>
                <input type="text" name="" id="editFirstname_'.$data['id'].'" class="'.$textfield.'" value="'.$data['firstname'].'" />
            </td>
            <td>
                <span id="lastname_'.$data['id'].'">
                    '.$data['lastname'].'
                </span>
                <input type="text" name="" id="editLastname_'.$data['id'].'" class="'.$textfield.'" value="'.$data['lastname'].'" />
            </td>
            <td><span id="loa_'.$data['id'].'">
                            '.$data['loa'].'
                        </span>';
                    /*$levelID = $data['userlevel_id'];
                    $getUserLevel = $db->query("SELECT * FROM tbuserlevel WHERE id='$levelID'","array");
                    foreach($getUserLevel as $dataUserLevel)
                    {
                        $finaldata.='
                        <span id="loa_'.$data['id'].'">
                            '.$data['loa'].'
                        </span>';
                    }
                    */
                    $finaldata.='
                    <select class="'.$selection.'" id="editLOA_'.$data['id'].'">';
                        $userLevel = $db->query("SELECT * FROM tbuserlevel","array");
                        foreach($userLevel as $dataLevel)
                        {
                            $level = $dataLevel['id'];
                            $finaldata.="<option value='".$dataLevel['id']."'";
                            if($levelID==$level)
                            {
                                $finaldata.= "selected=selected";
                            }
                            $finaldata.= ">".$dataLevel['userlevel']."</option>";
                        }
                    $finaldata.='
                    </select>';
            $finaldata.='</td>
            <td >
                <span id="password_'.$data['id'].'" >
                    *************
                </span>
                <input type="password" name="" id="editPassword_'.$data['id'].'" class="'.$textfield.'" value="" style="width:250px;"/>
            </td>
            <td id="edit_'.$data['id'].'" class="actions">
                <img src="/images/icon/edit.png" title="Edit user information." id="editUser_'.$data['id'].'" rel="'.$data['id'].'" class="editUser cursor"/>
            </td>
            <td id="editDel_'.$data['id'].'" class="actions">
                <img src="/images/icon/delete.png" title="Delete this user." id="deleteUser_'.$data['id'].'" rel="'.$data['id'].'" class="deleteUser cursor"/>
            </td>
            <td id="save_'.$data['id'].'" class="display actions" colspan="2">
                <img src="/images/icon/saving.png" title="Save edited user." id="saveUser_'.$data['id'].'" rel="'.$data['id'].'" class="saveUser cursor"/>
            </td>
        </tr>';
        }
        pagination($cur_page,$page,$per_page,$start,$previous_btn,$next_btn,$first_btn,$last_btn,$no_of_paginations,$finaldata,$count,$action,$value);
        }else{
            $finaldata.="<tr><td colspan='5'><center>No Record Found</center></td></tr>";
            echo $finaldata;
        }
    }
}
